package cn.tangwei.basic.controller;

import cn.tangwei.basic.utils.AjaxRusult;
import cn.tangwei.basic.utils.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsContorller {

    /**
     * 文件上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxRusult uplouad(@RequestPart(required = true, value = "file") MultipartFile file){
        try {
            // 获取文件名
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            // 获取文件后缀，substring是含头不含尾，最有回去下标lastIndexOf要加一
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxRusult.me().setResultObj(path);// 返回文件上传路径
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxRusult.me().setMessage("系统繁忙，稍后重试");
        }
    }

    /**
     * 删除文件接口
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxRusult delete(@RequestParam(required = true, value = "path") String path){
        try {
            // 获取文件名后缀
            String pathTmp = path.substring(1);// 截取掉路径的第一个/
            String groupPath = pathTmp.substring(0, pathTmp.indexOf("/"));// 截取第一个/前面的路径
            String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastDfsUtil.delete(groupPath, remotePath);
            return AjaxRusult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxRusult.me().setMessage("系统繁忙，稍后重试");
        }

    }

}
